package com.liao.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liao.common.constant.product.GenderEnum;
import com.liao.common.entity.member.UserEntity;
import com.liao.common.utils.PageUtils;
import com.liao.common.utils.Query;
import com.liao.member.dao.UserDao;
import com.liao.member.service.UserService;
import com.liao.member.utils.WechatUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;

import java.util.Map;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<UserEntity> page = this.page(
                new Query<UserEntity>().getPage(params),
                new QueryWrapper<UserEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public UserEntity Wxlogin(String code, String Pcode, String rawData, String signature) {


        // 用户非敏感信息：rawData
        // 签名：signature
        JSONObject rawDataJson = JSON.parseObject(rawData);
        // 1.接收小程序发送的code
        // 2.开发者服务器 登录凭证校验接口 appi + appsecret + code
        JSONObject SessionKeyOpenId = WechatUtil.getSessionKeyOrOpenId(code);
        // 3.接收微信接口服务 获取返回的参数
        String openid = SessionKeyOpenId.getString("openid");
        String sessionKey = SessionKeyOpenId.getString("session_key");

        // 4.校验签名 小程序发送的签名signature与服务器端生成的签名signature2 = sha1(rawData + sessionKey)
        String signature2 = DigestUtils.sha1Hex(rawData + sessionKey);
        if (!signature.equals(signature2)) {
//            return R.error("签名校验失败");
            throw new RuntimeException("签名校验失败");
        }


//         5.根据返回的User实体类，判断用户是否是新用户，是的话，将用户信息存到数据库；
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("open_id", openid);
        UserEntity user = baseMapper.selectOne(queryWrapper);
        if (user == null) {
            String phone = WechatUtil.getPhone(Pcode);
            // 用户信息入库
            String nickName = rawDataJson.getString("nickName");
            String avatarUrl = rawDataJson.getString("avatarUrl");
            user = new UserEntity();
            user.setOpenId(openid);
            user.setAvatar(avatarUrl);
            String subPhone = phone.substring(0, 3) + "****" + phone.substring(7, 11);
            user.setUsername(subPhone);
            user.setPhone(phone);
            user.setGender(GenderEnum.MALE);
//            user.setToken(StpUtil.getTokenInfo().tokenValue);
            save(user);
        } else {
            // 更新用户信息
//            user.setToken(StpUtil.getTokenInfo().tokenValue);
        }


        return user;

    }

}